<template>
        <div class="bubble-wrap" @click="click()"  >
            <span class="bubble bubble-blue" v-bind:style="{ background: bgcolor}">
            <span class="bubble-tail"></span>
            <span class="wave1" v-show="wave1Show"></span>
            <span class="wave2" v-show="wave2Show"></span>
            <span class="wave3" v-show="wave3Show"></span>
            <span  v-bind:style="{ color: color}">{{typeof(title)=='undefined'?'免费偷听':title}}</span></span>
            <audio class="answer-audio" :src="mp3_url" >
            </audio>
        </div>
</template>
<script>
    import {
        showLoading
    } from '../js/dialogUtil.js'

    export default {
        props: ['title', 'src', 'bgcolor', 'color', 'id'],
        data: function() {
            return {
                mp3_url: '',
                isPlaying: false,
                audio: undefined,
                wave1Show: false,
                wave2Show: false,
                wave3Show: true,
                count: 0,
                currentTime: 0,
                duration: 0
            }
        },
        created: function() {},
        methods: {
            click: function() {
                // let r = ;
                console.log(this.id)
                let reg = new RegExp(/^\d+$/);
                if (!reg.test(this.id)) {
                    this.$vux.alert.show({
                        title: '错误提示！',
                        content: '答案音频格式错误！！'
                    })
                    return;
                }
                if (this.mp3_url.length > 0) {
                    //检测是否播放完毕
                    if (this.audio.ended) {
                        this.audio.load();
                        return;
                    }
                    if (this.audio.paused) {
                        this.audio.play();
                    } else {
                        this.audio.pause();
                    }
                    this.$emit('click');
                } else {
                    let vm = this;
                    vm.$vux.loading.show({
                        text: '正在验证支付权限...'
                    })

                    let params = {
                        do: 'checkAnswerAuthority',
                        answer_id: this.id
                    };

                    vm.$http.jsonp(vm.url.acid, {
                        params: params
                    }).then(response => {
                        vm.$vux.loading.hide()
                        let data = response.body;
                        if (data.status == 'success') {
                            vm.$emit("listenCountIncrease", true);
                            // console.log(this.audio);
                            vm.mp3_url = data.url;
                            // vm.click();
                        } else {
                            vm.$vux.loading.show({
                                text: '正在生成订单!!'
                            })

                            vm.$http.get(vm.url.acid + "&do=initpay&answer_id=" + vm.id).then(response => {
                                vm.$vux.loading.hide()
                                let body = JSON.parse(response.body);
                                // console.log(body)
                                if (body.status == 'success') {
                                    vm.wx.chooseWXPay({
                                        timestamp: body.info.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                        nonceStr: body.info.nonceStr, // 支付签名随机串，不长于 32 位
                                        package: body.info.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                                        signType: body.info.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                                        paySign: body.info.paySign, // 支付签名
                                        success: function(res) {
                                            // 支付成功后的回调函数
                                            // 简单直接传url
                                            vm.$emit("listenCountIncrease", true);
                                            vm.mp3_url = body.info.url;
                                        },
                                        fail: function(res) {

                                            vm.$vux.alert.show({
                                                title: '错误提示！',
                                                content: '调起支付失败!' + JSON.stringify(res)
                                            })
                                        }
                                    });

                                } else {
                                    vm.$vux.alert.show({
                                        title: '错误提示！',
                                        content: '生成订单失败!'
                                    })
                                }

                            }, response => {
                                vm.$vux.loading.hide()
                                vm.$vux.alert.show({
                                    title: '错误提示！',
                                    content: '网络连接失败，请连网后重试'
                                });
                            });
                        }
                    }, response => {
                        vm.$vux.loading.hide()
                        vm.$vux.alert.show({
                            title: '错误提示！',
                            content: '网络连接失败，请连网后重试'
                        })

                    });
                }
            },
            addListener: function() {
                this.audio.addEventListener('timeupdate', this._handlePlayingUI)
                this.audio.addEventListener('loadeddata', this._handleLoaded)
                this.audio.addEventListener('pause', this._handlePlayPause)
                this.audio.addEventListener('play', this._handlePlayPlay)
                this.audio.addEventListener('ended', this._handlePlayEnd)
            },
            _handlePlayingUI: function(e) {
                switch (this.count % 6) {
                    case 0:
                        this.wave1Show = true;
                        this.wave2Show = false;
                        this.wave3Show = false;
                        break;
                    case 2:
                        this.wave2Show = true;
                        this.wave1Show = false;
                        this.wave3Show = false;
                        break;
                    case 4:
                        this.wave3Show = true;
                        this.wave1Show = false;
                        this.wave2Show = false;
                        break;
                }
                this.count++;
                // if (this.count == 6) this.count = 0;
            },
            _handleLoaded: function(e) {
                // console.log(this.audio);
                //加载完成就开始播放
                // this._handlePlayPlay();
                this.audio.play();

            },
            _handlePlayPause: function(e) {
                // console.log(this.audio);
            },
            _handlePlayPlay: function(e) {
                // this.audio.play();
                // console.log(this.audio)
                this.bus.$emit('stopAudio', this.id);

            },
            _handlePlayEnd: function(e) {
                let vm = this;
                this.wave3Show = true;
                this.wave1Show = false;
                this.wave2Show = false;
                vm.$vux.toast.show({
                    position: 'middle',
                    text: '音频播放结束',
                    type: 'text'
                })
                setTimeout(function() {
                    vm.$vux.toast.hide()
                }, 1000)

            }
        },
        mounted() {
            let vm = this;
            // console.log(vm)
            vm.audio = vm.$el.querySelectorAll('audio')[0];
            vm.addListener();
            vm.bus.$on('stopAudio', function(id) {
                console.log(id);
                //判断是不是本个音频
                if (vm.id == id) {
                    return;
                } else {
                    if (!vm.audio.paused) {
                        console.log("paused success");
                        vm.audio.pause();
                    }
                }

            })
        },
        beforeDestroy() {
            if (!this.audio.paused) {
                this.audio.pause();
            }
            this.audio.removeEventListener('timeupdate', this._handlePlayingUI)
            this.audio.removeEventListener('loadeddata', this._handleLoaded)
            this.audio.removeEventListener('pause', this._handlePlayPause)
            this.audio.removeEventListener('play', this._handlePlayPlay)
            this.audio.removeEventListener('ended', this._handlePlayEnd)
        }

    }
</script>
<style scoped>
    .bubble-wrap {
        display: inline-block;
        vertical-align: middle;
        cursor: pointer;
    }
    
    .bubble.bubble-blue {
        background: #28aef5;
    }
    
    .bubble {
        float: left;
        display: block;
        background: #1ccda6;
        line-height: 2.2rem;
        height: 2.2rem;
        border-radius: 1.1rem;
        text-align: center;
        min-width: 9rem;
        color: #fff;
        font-size: .8rem;
        text-decoration: none;
        position: relative;
        margin-right: .35rem;
    }
    
    .bubble .bubble-tail {
        width: .83rem;
        height: 1.185rem;
        position: absolute;
        bottom: 0;
        left: -.3rem;
        background-image: url("/fengshui/static/pic/bubble-tail.png");
        background-size: .83rem 1.185rem;
    }
    
    .bubble .wave1,
    .bubble .wave2,
    .bubble .wave3 {
        display: block;
        width: .8rem;
        height: .8rem;
        background-size: .8rem;
        position: absolute;
        top: .65rem;
        left: .65rem;
    }
    
    .bubble .wave1 {
        background-image: url("/fengshui/static/pic/bubble-wave1.png");
    }
    
    .bubble .wave2 {
        background-image: url("/fengshui/static/pic/bubble-wave2.png");
    }
    
    .bubble .wave3 {
        background-image: url("/fengshui/static/pic/bubble-wave3.png");
    }
</style>